import os
import time
from datetime import datetime, timedelta
import pandas as pd
from chinese_calendar import is_workday
from selenium.webdriver.support.ui import Select
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By

from cfg import user, pwd


class WebAuto:
    def __init__(self, filename):
        self.user = user
        self.pwd = pwd
        self.file_path = filename

    def login(self):
        url = 'http://www.hb.cmcc/typt/wps/myportal/!ut/p/a1/hY7NDoIwEISfxUOvdBGp6K3-JIgoQUPEXgwQBAzQplQJby-SmHjQOLedfLMzmOEQszp6FFmkCl5H5etm5GL6-toeL8HxVgcKdEo2_mrnAhCjB849AD9E4V_-hNmAgG0RnU50z9sFC_CPgRvMtqZh7ckb-F3hYJaVPB7mnmkdG1aGmUyvqUyldpe9nSsl5ggQtG2r5bGWVEmCQHVC9ZZoEFSd4FJ9_5DzRuHwI4lFFcLNLB8uHY2eACHWGw!!/dl5/d5/L2dBISEvZ0FBIS9nQSEh/'
        service = Service(r'webrpa/driver/msedgedriver.exe')
        self.chrome = webdriver.Edge(service=service)
        self.chrome.get(url)
        self.chrome.find_element(By.ID, 'loginUserName').send_keys(self.user)
        self.chrome.find_element(By.ID, 'loginPassword').send_keys(self.pwd)
        self.chrome.find_element(By.ID, 'obj_login').click()

    # 切换窗口
    def switch_new_window(self, handle):
        # 获取所有窗口句柄
        all_window_handles = self.chrome.window_handles
        # 切换到新窗口
        self.chrome.switch_to.window(all_window_handles[handle])

    # 获得当前活动窗口url
    def get_current_url(self):
        return self.chrome.current_url

    # 移除只读属性
    def remove_readonly(self, id):
        # 使用 JavaScript 移除 readonly 属性
        readonly_field = self.chrome.find_element(By.ID, id)
        js = f'document.getElementById("{id}").removeAttribute("readonly");'

        self.chrome.execute_script(js)
        # self.chrome.execute_script("arguments[0].removeAttribute('type');", readonly_field)

    def get_next_work_day(self, time_day,num):
        """
        # 获取上一个工作日
        """
        next_worker_day = ""

        # 最多查询20次
        query_time = 0

        while True:
            time_day = time_day + timedelta(days=num)

            if is_workday(time_day):
                next_worker_day = time_day.strftime("%Y-%m-%d")
                break
            elif query_time > 31:
                break

            query_time += 1

        return next_worker_day

    # 设置入园起止日期
    def set_date(self,num):
        # 获取当前日期和时间
        current_date = datetime.now().date().today()
        # 格式化日期
        endtime = self.get_next_work_day(current_date,num)
        self.starttime = current_date.strftime("%Y-%m-%d")
        self.endtime = endtime

    # 办理入园信息提交
    def msg_submit(self):

        df = pd.read_excel(self.file_path)
        # 切换到点击临时入园句柄
        self.switch_new_window(1)
        self.chrome.find_element(By.XPATH, "//*[contains(text(), '临时入园')]/..").click()
        # 切换到信息提交句柄窗口
        self.switch_new_window(2)
        # 定位下拉框
        dropdown = self.chrome.find_element(By.ID, 'SHOW_DB_APPLY_TYPE_NAME')
        select = Select(dropdown)
        select.select_by_visible_text('有人来访')
        # 填写起止日期
        # 移除只读属性
        self.remove_readonly('SHOW_DB_VISITORS_DATE')
        self.remove_readonly('SHOW_DB_VISITORS_END_DATE')

        start_time = self.chrome.find_element(By.ID, 'SHOW_DB_VISITORS_DATE')
        start_time.clear()
        start_time.send_keys(self.starttime)
        start_time.click()
        end_time = self.chrome.find_element(By.ID, 'SHOW_DB_VISITORS_END_DATE')
        end_time.clear()
        end_time.send_keys(self.endtime)
        end_time.click()
        self.chrome.find_element(By.ID, 'DB_VISITORS_USER_COUNT').send_keys(df.shape[0] - 2)
        # 入园事由
        self.chrome.find_element(By.ID, 'DB_ORDER_REMARK').send_keys('工作')
        # 上传入园名单
        self.chrome.find_element(By.ID, 'excelVistorDataButton').click()
        time.sleep(1)
        self.chrome.find_element(By.XPATH, '//*[@id="tipModal"]/div/div/div[3]/button').click()
        time.sleep(1)
        # 文件
        # self.chrome.find_element(By.ID, 'chooseFile').send_keys(self.file_path)
        # self.chrome.find_element(By.ID, 'confirmImportBtn').click()
        # time.sleep(1)
        # self.chrome.find_element(By.XPATH, '//*[@id="bsmodal"]/div/div/div[3]/button').click()
        # time.sleep(1)
        # self.chrome.find_element(By.ID, 'submitApplyBtn').click()
        # time.sleep(1)
        # self.chrome.find_element(By.XPATH, "//*[contains(text(), '湛颖')]/../td[4]").click()
        # time.sleep(1)
        # self.chrome.find_element(By.XPATH, '//*[@id="bsmodal"]/div/div/div[3]/button').click()
        time.sleep(80000)
        # self.chrome.quit()


if __name__ == '__main__':
    auto = WebAuto(1)
    auto.login()
    auto.set_date()
    auto.msg_submit()
    time.sleep(8000)
